<template>
  <div class="q-pa-md">
    <div class="q-pa-md q-gutter-sm">
        <q-btn color="primary" label="添加" @click="addUser"/>
        <q-btn color="secondary" label="修改" @click="updateUser"/>
        <q-btn color="deep-orange" label="删除" @click="deleteUser"/>
    </div>

    <q-table
      title="用户管理"
      :rows="data"
      :columns="columns"
      row-key="id"
      selection="single"
      v-model:selected="selected"
    />

    
    <q-dialog v-model="confirm" persistent>
        <q-card>
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">用户信息</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section>
            <div class="q-pa-md" style="min-width: 500px">

              <q-form
                ref="myForm"
                @reset="onReset"
                class="q-gutter-md"
              >

              <q-input
                filled
                v-model="name"
                label="姓名 *"
                lazy-rules
                :rules="[ val => val && val.length > 0 || '姓名不能为空']"
              />

              <q-input
                filled
                v-model="address"
                label="地址 *"
                lazy-rules
                :rules="[ val => val && val.length > 0 || '地址不能为空']"
              />
              <q-input
                filled
                type="number"
                v-model="age"
                label="年龄 *"
                lazy-rules
                :rules="[
                  val => val !== null && val !== '' || '年龄不能为空',
                  val => val > 0 && val < 100 || '请输入一个合法的年龄'
                ]"
              />

      <div>
        <q-btn label="提交"  color="primary" @click="onsubmit"/>
        <q-btn label="重置" type="reset" color="primary" flat class="q-ml-sm" />
      </div>
    </q-form>

  </div>

        
        </q-card-section>
      </q-card>
    </q-dialog>


     <q-dialog v-model="alert">
      <q-card>
        <q-card-section>
          <div class="text-h6">提示</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          请选择一条数据进行处理。
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="OK" color="primary" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-dialog v-model="deleteConfirm" persistent>
      <q-card style="width: 500px; max-width: 60vw;">
        <q-card-section class="row items-center">
          <q-avatar icon="signal_wifi_off" color="primary" text-color="white" />
          <span class="q-ml-sm">您确认删除吗?</span>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="确认" color="primary" v-close-popup  @click="deleteUserRest"/>
        </q-card-actions>
      </q-card>
    </q-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
      columns: [
        {
          name: 'index',
          label: '序号',
          field: 'index'
        },
        { name: 'name', label: '姓名', field: 'name', sortable: true },
        { name: 'address', label: '地址', field: 'address', sortable: true },
        { name: 'age', label: '年龄', field: 'age' }
      ],
      data: [
                
      ],
      confirm: false,
      alert:false,
      deleteConfirm:false,
      name:"",
      address: "",
      age:"",
      userId:"",
      selected: [],
    }
  },
  mounted () {
      this.refreshData()
  },
  methods : {
    refreshData() {
        this.$api.get('/api/v1/users/')
        .then((response) => {
          console.log(response.data);
          let data = response.data.data;

          data.forEach((row, index) => {
            row.index = index+1;
          })
          this.data = data;
        })
        .catch(() => {
          console.log("error")
        })
    },

    onsubmit (){
        
        this.$refs.myForm.validate().then(success => {
            if (success) {
                this.confirm = false;
                let data = {
                  name : this.name,
                  address : this.address,
                  age : this.age
                };
                if(this.userId){
                   this.$api.put('/api/v1/users/' + this.userId, data)
                  .then((response) => {
                      this.refreshData();
                  })
                  .catch(() => {
                    console.log("error")
                  })

                }else{
                    
                     this.$api.post('/api/v1/users/', data)
                    .then((response) => {
                        this.refreshData();
                    })
                    .catch(() => {
                      console.log("error")
                    })
                }
               
            }
            else {
              console('表单验证不通过');
            }
        })      
    },

    onReset(){
          this.$refs.myForm.resetValidation();
    },

    addUser(){
      this.confirm = true;
      this.name = "";
      this.address = "";
      this.age = "";
      this.userId = "";
    },

    updateUser(){
      if(!this.selected[0]){
        this.alert = true;
      }else{
          this.userId = this.selected[0].id;
          this.name = this.selected[0].name;
          this.address = this.selected[0].address;
          this.age = this.selected[0].age;
          this.confirm = true;
      }
    },

    deleteUser(){
      if(!this.selected[0]){
        this.alert = true;
      }else{
        this.userId = this.selected[0].id;
        this.deleteConfirm = true;
      }
    },

    deleteUserRest(){
      if(this.userId){
          this.$api.delete('/api/v1/users/' + this.userId)
            .then((response) => {
                this.userId = "";
                this.deleteConfirm = false;
                this.refreshData();
            })
            .catch(() => {
              console.log("error")
            })
      }
    }
  }
}
</script>